﻿
$("#CancelId").click(function ()//点击“取消”按钮时返回试题列表
{
    window.location.href = "/TeacherManger/testlib?CourseID=" + $("#HiddenCourseID").val();
});

$("#SubmitId").click(function ()//点击“确定”按钮时返回列表
{
    window.location.href = "/TeacherManger/testlib?CourseID=" + $("#HiddenCourseID").val();
});


        
function tempSelectedClass(){
    this.Id = -1;
    this.STitle = '';
    this.IParentID = '';
    this.ILevel = '';
    this.ISort = '';
    this.IDeanCourseID = '';
    this.IHourse = '';
    this.SUrl = '';
    this.SIntrodece = '';
    this.SCaptailName = '--请选择节--';

    }
var tempJid = '';
    var getQuestionKind;//当前试题类型
    var gdViewModel;
    var tempCheckedID = '';
    $(function () {

        $("#submitform").validate({
            rules: {
                TitleId: { required: true, maxlength: 100 }

            },
            messages: {


                TitleId: { required: "<font color='red'>标题为必填项</font>", maxlength: "<font color='red'>标题最大长度不能超过100</font>" }

            }
        });
        var ue = new baidu.editor.ui.Editor({ maximumWords: 1000 });//内容使用的编辑器声明

        ue.render("editorId");//内容编辑
        //点击编辑图标进行内容编辑
        $("#edit").click(function () {
            var css = $("#editorId").css("display");
            if (css == "block") {
                $("#editorId").hide();
            } else if (css == "none") {
                $("#editorId").show();
            }
        })


        function gridViewModel() {
            var self = this;


            self.recordSet = ko.observableArray(); //选项数据集

            self.IsOpenSet = ko.observable();
           
            self.AnswerRecordSet = ko.observableArray(); //选项数据集  new add
            self.CurrentCSession = ko.observable();
            //作为显示数据的表格的头部：显示文字和对应的字段名（辅助排序）
            self.headers = ko.observableArray(
                 [
     { displayText: '选项', value: 'SOptionName', width: 'auto' },
     { displayText: '是否正确答案', value: 'IIsTrue', width: 'auto' }
                 ]
                );

            //CRUD均通过ajax调用实现，这里提供用于获取ajax请求地址的方法

            //节点数据
            self.NodeValue = ko.observable({
                Id: '',
                ICousreId: '',
                SCourseCode: '',
                IProblemType: '',
                STitle: '',
                SContent: '',
                IStuOpen: '',
                SAnswer: '',
                ITeaCatalog: '',
                IHardLevel: '',
                IDiffLevel: '',
                SPointers: '',
                SKeyWords: '',
                SCharpter: '',
                SAnalysis: '',  //答案解析

            }),

            //初始化
            self.init = function () {
                self.getCurrentQuestion();

            }
            self.initEd = function () {//结束初始化
            }
            //获取当前点击选中的试题详细信息  
            self.getCurrentQuestion = function () {
                $.ajax(
                    {
                        async: false,
                        url: '/api/TestLibExt/GetPreviewData/',
                        type: "get",
                        success: function (result) {
                            self.NodeValue(result.PreviewLib);  //把获得的TestLib表中当前试题信息放到nodevalue
                     
                            getQuestionKind = result.PreviewLib.IProblemType;
                            var ProblemType = self.NodeValue().IProblemType;
                            self.NodeValue().IProblemType = self.ChangeProblemType(ProblemType);//转换试题类型的为对应的字符串
                            var tempcharpter = self.NodeValue().SCharpter;
                            if (tempcharpter != '' && tempcharpter != null && typeof(tempcharpter)!='undefined') {
                                var tempStr = tempcharpter.indexOf('章');
                                tempStr++;
                                var TestStr = tempcharpter.substring(0, tempStr);
                                $("#txtbSrSCharpter option[value=" + TestStr + "]").attr("selected", true)//绑定章
                            }
                        
                            tempJid = self.NodeValue().ITeaCatalog;
                            
                            self.myChange();
                            
                          
                            var val = result.PreviewLib.IHardLevel; //你后台的值是3
                            if (result.PreviewLib.IHardLevel != 0) {
                                $("input:radio[name='stars-rating'][ value='" + val + "']").attr("checked", true);

                            }
                            //区分度

                            var vall = result.PreviewLib.IDiffLevel; //你后台的值是3
                            if (result.PreviewLib.IDiffLevel != 0) {

                                $("input:radio[name='rating'][ value='" + vall + "']").attr("checked", true);

                            }

                            if (getQuestionKind == 1 || getQuestionKind == 2) //单选题或者多选题
                            {


                                $("#OptionId").show();//显示选择题选项的div 
                                self.search();
                                $("#QuesAnswerId").hide();//隐藏判断题答案选择的div
                                $("#ContentId").hide();//隐藏内容
                            }
                            else {
                           
                           
                                $("#OptionId").hide();//隐藏选择题选项的div
                                self.TFsearch();
                                $("#QuesAnswerId").show();//显示判断题答案选择的div

                                if (self.NodeValue().SContent != null)  //当前试题存在内容
                                {

                                    $("#editorId").show(); //显示编辑器
                                    ue.ready(function () {  //修正ueditor未加载完成对其加载内容报错问题
                                        ue.setContent(self.NodeValue().SContent);//把当前试题的内容存放到编辑器中
                                    });

                                }

                            }


                        }
                    })

            }


            //初始化判断题查询 10.3/test
            self.TFsearch = function () {

                $.ajax(
                {

                    url: '/api/TestLibExt/FindOption/',
                    type: "get",
                    async: false,
                    complete: function () {  //当数据加载完成，取消遮罩  by zjb
                        if (self.tableMaskElement) {
                            self.tableMaskElement.unmask();
                        };
                    },
                    success: function (result) {
                        $.each(result, function (m, n) {
                         //绑定选中的判断题的正确与否
                            $("#trTFrecordSet").append("<td style='width: 200px;float:left'> <label class='radio state-success'><input type='radio' name='answerRadio' value='" + n.Id + "'> <i></i><span data-bind='" + n.SOptionName + "'>"+n.SOptionName+"</span></label> </td>");

                         
                            if (typeof (n.IIsTrue) != 'undefined' && n.IIsTrue != '') {
                                $("input:radio[name='answerRadio'][ value='" + n.Id + "']").attr("checked", true);
                             

                            }
                
                        }
                        );

                    }

                });
          

            };

            //初始查询
            self.search = function () {

                $.ajax(
                {

                    url: '/api/TestLibExt/FindOption/',
                    type: "get",

                    complete: function () {  //当数据加载完成，取消遮罩  by zjb
                        if (self.tableMaskElement) {
                            self.tableMaskElement.unmask();
                        };
                    },
                    success: function (result) {
                        self.recordSet(result);//收集返回的选项集


                        $(".optionName").editable();
                        $(".optionAns").editable({
                            source: [{ value: 1, text: '正确' }, { value: 0, text: '错误' }]
                            , success: function (response, newValue) {
                                gdViewModel.search();
                            }
                        });



                    }
                });
            };






            //TO Add Method
            self.CurrentSelected = ko.observableArray();
            self.chaptesr = ko.observableArray();

            //在被选章里面绑定节
            ;
            self.arrayBindSesson = ko.observableArray();
            self.selectedchapter = ko.observableArray();//当前被选中的章
            self.myChange = function (a, b, c, d) {//改变所选章时移动

                //self.arrayBindSesson.removeAll();//移除绑定的节

                var selV = $("#txtbSrSCharpter").find("option:selected").attr("data-value");
               
                //var tempInsert = new tempSelectedClass();
                //self.arrayBindSesson.push(tempInsert);
                //if (typeof (tempJid) == 'undefined' || tempJid == '' || tempJid==null)
                //{
               
                    
                //    self.CurrentSelected(tempInsert.Id);
                //}

                $("#txtbSrITeaCatalog").empty();
                $("#txtbSrITeaCatalog").append("<option value='-1' >---请选择节---</option>")
                //在没有默认选中的情况下暂时不知该做何处理
                if (selV != '' && selV != null && typeof (selV) != 'undefined') {
                   
                    $.getJSON("/api/TestLibExt/GetSession?ID=" + selV, null, function (data) {
                        $.each(data, function (m, n) {
                          
                                $("#txtbSrITeaCatalog").append("<option value='" + n.Id + "' >" + n.SCaptailName + "</option>");

                         
                            if (n.Id == tempJid && typeof (tempJid) != 'undefined' && tempJid != '') {
                               
                                 $("#txtbSrITeaCatalog option[value='" + tempJid + "']").attr("selected", true)//绑定章
                                
                                tempJid = '';
                            }
                          


                        });

                    });
                   
                    
                }
            };


            //删除选中的选项 
            self.DeleteModel = function (currentOption) {

                var optionID = currentOption.Id;

                if (optionID != null && typeof (optionID) != "undefined" && optionID != "") {
                    $.ajax({
                        url: '/api/TestLibExt/DelOptions?id=' + optionID,
                        type: "POST",
                        success: function () {
                            alert("删除数据成功！");
                            self.search();
                        }
                    })
                }

            }



            //新增选项
            self.DataAddModel = function () {
                $.ajax({
                    url: "/api/TestLibExt/AddOptions/",
                    type: "POST",
                    success: function (result) {

                        self.search();
                        alert("新增选项成功！");

                    }
                })
            }






            //转换试题类型的为对应的字符串
            self.ChangeProblemType = function (kind) {
                var changetype;
                switch (kind) {
                    case 1:

                        changetype = "单选题";

                        break;
                    case 2:
                        changetype = "多选题";
                        break;
                    case 3:
                        changetype = "判断题";
                    default: break;
                }
                return changetype;
            }




            //验证标题是否合法
            self.QuesDataValidate = function () {
                if ($("#TitleId").val() == "" || typeof ($("#TitleId").val()) == 'undefined') {
                    alert("标题不能为空，请填写！");
                    return 0;
                }
                else
                    return 1;

            }




            //验证单选题的选项设置是否合法，不能全错 
            self.OptionsValidate = function () {
                var bol;
                $.ajax({
                    async: false,  //设置为同步加载
                    url: '/api/TestLibExt/OptionsValidate/',
                    type: "POST",
                    success: function (result) {
                        if (result == 0) {
                            alert("单选不能全为错，请重新填写！");
                            bol = 0;
                        }
                        else
                            bol = 1;
                    }
                });
                return bol;
            }



            //取页面上的数据项
            self.CommonData = function () {

                self.NodeValue().STitle = $("#TitleId").val();//从标题编辑栏里面获取值
                self.NodeValue().SPointers = $("#SPointersId").val();//获取知识点
                var IStuOpen = $('input:checkbox[name="checkbox-toggle"]:checked').val();//获取是否公开的ON/OFF
                var IHardLevel = $('input:radio[name="stars-rating"]:checked').val();//获取难易度rating
                var IDiffLevel = $('input:radio[name="rating"]:checked').val();//获取区分度

                var AnswerAnalysis = $("#AnswerAnalysis").val();  //获取题目的答案解析  添加于12.2

                var Charpter = $("#txtbSrSCharpter").find("option:selected").attr("value");//获取章optionsText
                var Test = $("#txtbSrITeaCatalog").find("option:selected").attr("value");//获取节
                self.NodeValue().ITeaCatalog = Test;
                self.NodeValue().SCharpter = Charpter;
                self.NodeValue().SAnalysis = AnswerAnalysis;  //答案解析  添加于12.2

                //判断是否对学生公开
                if (IStuOpen == 1) {
                    self.NodeValue().IStuOpen = 1;//对学生公开
                }
                else {
                    self.NodeValue().IStuOpen = 0;//不对学生公开
                }
                //获取试题的难易度
                if (typeof (IHardLevel) != "undefined") {

                    self.NodeValue().IHardLevel = IHardLevel;//获取难易度
                }
                else {
                    self.NodeValue().IHardLevel = 0;
                }
                //获取试题的区分度
                if (typeof (IDiffLevel) != "undefined") {

                    self.NodeValue().IDiffLevel = IDiffLevel;//区分度
                }
                else {
                    self.NodeValue().IDiffLevel = null;
                }
                /*--/获取所有试题共同部分*/
                var kind = getQuestionKind;//获取当前的题型选项
                switch (kind) {
                    case 1:
                        //单选
                    case 2:
                        //多选
                        break;
                    case 3:  //判断 
                        var SAnswer = $('input:radio[name="answerRadio"]:checked').val();//获取判断题的正确答案
                        $.ajax({
                            type: "POST",
                            async: false,
                            url: "/api/TestLibExt/ChangeTFOption/",
                            data: { ID: SAnswer },
                            success: function (data) {
                                self.NodeValue().SAnswer = data.SOptionName;
                            }
                        });

                        self.NodeValue().SContent = ue.getContent();//从内容编辑栏中获取数据
                        break;
                    default:
                        break;
                }


            }




            //从页面获取数据，同时更新到数据库
            self.QuestionDataUpdate = function () {

                self.CommonData(); //取页面上共有的数据项


                $.ajax({
                    url: '/api/TestLibExt/QuestionUpdate/',
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(self.NodeValue()),
                    success: function () {
                        self.PreviewData();

                    }
                })



            }




            //设置选项正确与错误图标
            self.formatIsTrue = function (value) {
                if (value == 1)
                    return "<i class='glyphicon glyphicon-ok ' style='color:green;'></i>";
                else
                    return "<i class='glyphicon glyphicon-remove ' style='color:red;'></i>";
            }

            //获取试题预览数据  
            self.PreviewData = function () {

                $.ajax(
               {
                   url: '/api/TestLibExt/GetPreviewData/',
                   type: "POST",
                   success: function (result) {

                       var ProblemType = result.PreviewLib.IProblemType;
                       result.PreviewLib.IProblemType = self.ChangeProblemType(ProblemType);//转换试题类型的为对应的字符串

                       self.NodeValue(result.PreviewLib);//收集返回的试题信息


                       if (self.NodeValue().SContent != null) {//内容不为空，则内容div显示
                           $("#PrewContent").show();
                       }
                       else {
                           $("#PrewContent").hide();//内容为空，则内容div不显示
                       }

                       self.AnswerRecordSet(result.LibOptionList);//收集返回的正确选项集
                       //是否对学生公开IsOpenSet标记“是/否”
                       if (result.PreviewLib.IStuOpen == 1) {
                           self.IsOpenSet("是")
                       }
                       else {
                           self.IsOpenSet("否")
                       }

                       //难易度
                       var hardraido = $("input:radio[name='stars-show']"); //假设你的radio的name属性是 radio,用name选择器选择
                       var val = 10 - result.PreviewLib.IHardLevel; //你后台的值是3
                       if (result.PreviewLib.IHardLevel != 0) {
                           hardraido[val].checked = true; //选中第三个
                       }
                       //区分度
                       var showdif = $("input:radio[name='show']"); //假设你的radio的name属性是 radio,用name选择器选择
                       var vall = 10 - result.PreviewLib.IDiffLevel; //你后台的值是3
                       if (result.PreviewLib.IDiffLevel != 0 && result.PreviewLib.IDiffLevel != null) {
                           showdif[vall].checked = true; //选中第三个
                       }
                       if (getQuestionKind == 1 || getQuestionKind == 2) {
                           self.search();
                       }

                   }
               })

            }







            //点击下一步
            self.NexTStep = function ()//跳转预览页面
            {
                if (!self.QuesDataValidate()) {// 验证标题是否合法
                    return false;
                }
                if (getQuestionKind == 1) {
                    if (!self.OptionsValidate()) { //验证单选题的选项设置是否合法
                        return false;
                    }
                }

                self.QuestionDataUpdate(); //更新试题到数据库

                if (getQuestionKind == 1 || getQuestionKind == 2)  //当前试题的试题类型为单项选择或者多项选择
                {
                    $("#normalLib").hide(); //显示一般题型的答案的div隐藏
                }
                else {
                    $("#OptionList").hide();  //选项div隐藏
                    $("#optLib").hide();    //正确选项div隐藏
                }
                $("#CancelId").hide();
                $("#NextId").hide();
                $("#UpdateTestLb").hide();//隐藏编辑页面
                $("#PreviewTestLib").show();//显示预览div
                $("#SubmitId").show();//显示确定按钮
                $("#PreId").show();//显示上一步
            }

            //点击“上一步”按钮
            self.PreStep = function ()//返回编辑页面
            {
                $("#CancelId").show();
                $("#NextId").show();
                $("#UpdateTestLb").show();//隐藏编辑页面
                $("#PreviewTestLib").hide();//显示预览div
                $("#SubmitId").hide();//显示确定按钮
                $("#PreId").hide();//显示上一步
            }


        }



        var gdViewModel = new gridViewModel();



        gdViewModel.init();//初始化加载页面
        ko.applyBindings(gdViewModel);





    });





